package com.bsoft.android_js;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity{
    WebView mwebview;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mwebview = (WebView) findViewById(R.id.mwebview);


        // 启用javascript
        mwebview.getSettings().setJavaScriptEnabled(true);
        // 从assets目录下面的加载html
        mwebview.loadUrl("file:///android_asset/web.html");
        mwebview.addJavascriptInterface(MainActivity.this,"android");
        mwebview.setWebViewClient(new WebViewClient(){

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                mwebview.loadUrl(url);
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }
        });
    }

    //由于安全原因 targetSdkVersion>=17需要加 @JavascriptInterface
    //JS调用Android JAVA方法名和HTML中的按钮 onclick后的别名后面的名字对应
    @JavascriptInterface
    public void call_Android(){

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                startActivityForResult(new Intent(MainActivity.this,LoginActivity.class),100);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode){
            case 1000:
                String data2 = "我是孩子的ＩＤ";
                mwebview.loadUrl("javascript:postInfo('" + data2  + "')");
                break;
        }
    }
}
